package com.richrail.console;

import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;

import com.richrail.Depot;
import com.richrail.console.dsl.RichRailLexer;
import com.richrail.console.dsl.RichRailParser;
import com.richrail.model.entities.DepotStorage;

public class JavaExecutor implements Executor
{
	public JavaExecutor(DepotStorage depotStorage)
	{
		RichRailParser.setDepotStorage(depotStorage);
	}
	
	@Override
	public String execute(String input)
	{
		String response = null;
		
		try
		{
			RichRailLexer lexer = new RichRailLexer(new ANTLRStringStream(input));
			RichRailParser parser = new RichRailParser(new CommonTokenStream(lexer));
			parser.command();
			
			response = parser.response;
		}
		catch (RecognitionException e) {}
		
		if (response == null)
		{
			response = "command not correct";
		}
		
		return response;
	}
	
	public static void testCommands()
	{
		CLI cli = new CLI(new DepotStorage(new Depot()));
		
		testCommand(cli, "new train", "train tr1 created");
		testCommand(cli, "new train ctr", "train ctr created");
		testCommand(cli, "new wagon", "wagon wg1 created");
		testCommand(cli, "new wagon cwg", "wagon cwg created");
		testCommand(cli, "add wg1 to tr1", "wagon wg1 added to train tr1");
		testCommand(cli, "add wg1 to ctr", "wagon wg1 could not be added to train ctr");
		testCommand(cli, "getnumseats train tr1", "number of seats in train tr1: 20");
		testCommand(cli, "remove wg1 from tr1", "wagon wg1 removed from train tr1");
		testCommand(cli, "remove wg1 from tr1", "wagon wg1 could not be removed from train tr1");
		testCommand(cli, "getnumseats train tr1", "number of seats in train tr1: 0");
		testCommand(cli, "add wg1 to tr1", "wagon wg1 added to train tr1");
		testCommand(cli, "add cwg to tr1", "wagon cwg added to train tr1");
		testCommand(cli, "delete wagon cwg", "wagon cwg deleted");
		testCommand(cli, "delete wagon cwg", "wagon cwg does not exists");
		testCommand(cli, "delete train tr1", "train tr1 deleted");
		testCommand(cli, "add wg1 to ctr", "wagon wg1 added to train ctr");
	}
	
	public static void testCommand(CLI cli, String cmd, String expectedRes)
	{
		String res = cli.execute(cmd);
		
		if (!res.equals(expectedRes))
		{
			throw new AssertionError("Executed command '" + cmd + "' expected '" + expectedRes + "' but got '" + res + "'");
		}
	}
}
